<template>
  <view class="container">
    <view class="comment-box">
      <view class="score-box">
        <text>评分：</text>
        <view class="stars">
          <text
            v-for="i in 5"
            :key="i"
            class="star"
            :class="{ active: i <= score }"
            @tap="setScore(i)"
            >★</text
          >
        </view>
      </view>

      <view class="content-box">
        <textarea
          v-model="content"
          placeholder="请输入您的评价"
          maxlength="500"
        />
      </view>

      <view class="pic-box">
        <view class="upload-tip">上传图片（最多3张）</view>
        <view class="pic-list">
          <block v-for="(item, index) in pics" :key="index">
            <view class="pic-item">
              <image :src="item" mode="aspectFill" />
              <view class="delete" @tap="deletePic(index)">×</view>
            </view>
          </block>
          <view v-if="pics.length < 3" class="upload-btn" @tap="chooseImage">
            +
          </view>
        </view>
      </view>

      <view class="anonymous-box">
        <radio :checked="isAnonymous" @tap="toggleAnonymous" />
        <text>匿名评价</text>
      </view>

      <button class="submit-btn" :disabled="!canSubmit" @tap="submitComment">
        提交评价
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from "vue";
import { onLoad } from "@dcloudio/uni-app";

const orderNum = ref("");
const score = ref(0);
const content = ref("");
const pics = ref([]);
const isAnonymous = ref(false);

let orderItemId = '';

onLoad((options) => {
  orderItemId = options.orderItemId;
  console.log('接收到的订单ID:', orderItemId);
});

const setScore = (val) => {
  score.value = val;
};

const chooseImage = () => {
  uni.chooseImage({
    count: 3 - pics.value.length,
    sizeType: ["compressed"],
    sourceType: ["album", "camera"],
    success: (res) => {
      pics.value = pics.value.concat(res.tempFilePaths);
    },
  });
};

const deletePic = (index) => {
  pics.value.splice(index, 1);
};

const toggleAnonymous = () => {
  isAnonymous.value = !isAnonymous.value;
};

const canSubmit = computed(() => {
  return score.value > 0 && content.value.trim().length > 0;
});

const submitComment = () => {
    // 添加前置验证
    if (score.value < 1 || score.value > 5) {
    return uni.showToast({
      title: "请选择1-5星评分",
      icon: "none"
    });
  }
  uni.showLoading({ title: "提交中..." });

  http
    .request({
      header: {
        'Content-Type': 'application/json' // 明确指定请求格式
    },
      url: "/p/prodComm",
      method: "POST",
      data: {
        orderItemId: orderItemId,
        score: score.value,
        content: content.value,
        pics: '', // 转换为逗号分隔字符串
        isAnonymous: isAnonymous.value ? 1 : 0,
        evaluate: getEvaluateType(score.value)
      },
    })
    .then(() => {
      uni.showToast({ title: "评价成功" });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);

    })
    .catch((err) => {
      console.error("提交评论失败:", err);
      uni.showToast({
        title: err.data?.msg || "服务器出了点小差",
        icon: "none",
        duration: 2000,
      });
    })
    .finally(() => {
      uni.hideLoading();
    });
};

// 评价类型计算
const getEvaluateType = (score) => {
  if (score >= 4) return 0; // 好评
  if (score >= 2) return 1; // 中评
  return 2; // 差评
};
</script>

<style scoped lang="scss">
.container {
  padding: 20px;
}

.comment-box {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
}

.score-box {
  display: flex;
  align-items: center;
  margin-bottom: 20px;

  .stars {
    margin-left: 10px;

    .star {
      font-size: 24px;
      color: #ccc;
      margin-right: 5px;

      &.active {
        color: #f5a623;
      }
    }
  }
}

.content-box {
  textarea {
    width: 100%;
    height: 150px;
    padding: 10px;
    border: 1px solid #eee;
    border-radius: 4px;
    font-size: 14px;
  }
}

.pic-box {
  margin-top: 20px;

  .upload-tip {
    font-size: 12px;
    color: #999;
    margin-bottom: 10px;
  }

  .pic-list {
    display: flex;
    flex-wrap: wrap;

    .pic-item,
    .upload-btn {
      width: 80px;
      height: 80px;
      margin-right: 10px;
      margin-bottom: 10px;
      border: 1px dashed #eee;
      border-radius: 4px;
      position: relative;

      image {
        width: 100%;
        height: 100%;
        border-radius: 4px;
      }

      .delete {
        position: absolute;
        right: -8px;
        top: -8px;
        width: 20px;
        height: 20px;
        background: #f00;
        color: #fff;
        border-radius: 50%;
        text-align: center;
        line-height: 20px;
        font-size: 12px;
      }
    }

    .upload-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
      color: #999;
    }
  }
}

.anonymous-box {
  display: flex;
  align-items: center;
  margin: 20px 0;

  radio {
    transform: scale(0.8);
    margin-right: 5px;
  }
}

.submit-btn {
  background: #f5a623;
  color: #fff;
  border-radius: 4px;

  &[disabled] {
    background: #ccc;
  }
}
</style>
